<?php
/**
 * Created by PhpStorm.
 * Personal: Administrator
 * Date: 2018/7/31
 * Time: 13:40
 */
class MyprojectApp extends CommonApp {

    //我的项目-->学生
    public function studentAct(){
        $result = $this->checkLogin();
        //身份判定
        $this->is_student();
        $search['where'] = "1 ";
        //搜索条件
        $search['where'] .= "AND `parent_id`='{$result['memberid']}' ";
        //按申报时间
        if(My::is_id(My::arr2var($_GET,'year'))){
            $year = $_GET['year'];
            $search['where'] .= "AND `year`='{$year}' ";
        }else $search['where'] .= "AND `year`='".date("Y")."' ";
        //缓存时间
        $search['time'] = isset($_COOKIE['time']) ? $_COOKIE['time'] : strtotime(date("Y-m-d H:i:s"));
        $project = My::getCache($search,array('pre'=>'student'));
        if($project == ''){
            $project = DB('project')->where($search['where'])->find();//专业
            if($project){
                $project['params'] = My::decodeJson($project['params']);
                $project['members'] = My::decodeJson($project['members']);
            }
            $project['now_year'] = date("Y");
            $project['years'] = DB('project')->where("parent_id = {$result['memberid']}")->group('year')->field('year')->select();
            setcookie("time",$search['time'],null,'/');
            My::setCache($search,$project,array('pre'=>'student'));
//            echo '没缓存项目,在刷新下';
//            exit();
        }
        $this->assign('project',$project);//项目信息
        $this->assign('result',$result);//账号信息
        $this->display();
    }

    //项目详情
    public function detailAct(){
        $result = $this->checkLogin();
        //身份判定
        $this->is_student();
        if(My::is_id(My::arr2var($_GET,'id'))){
            $search['where'] = "parent_id = '{$result['memberid']}' ";
            if(My::arr2var($_GET,'year')!=''){
                $year = I('get.year');
                $search['where'] .= "AND year = '{$year}'";
            }else $search['where'] .= "AND  year = ".date("Y")."";
            $project = DB('project')->where($search['where'])->cache()->find();//专业
            $project['params'] = My::decodeJson($project['params']);
            $project['field'] = explode(",",$project['field']);
            $this->assign('project',$project);//项目信息
        }

        $this->assign('field',C('field'));
        $this->assign('result',$result);//账号信息
        $this->display();
    }

    //项目编辑
    public function modifyAct(){
        $result = $this->checkLogin();
        //身份判定
        $this->is_student();
        //项目名称
        if(!My::is_string($_POST['project']))
            $this->ajaxReturn(300,'请填写正确的项目名称！');
        if(empty($_POST['field']))
            $this->ajaxReturn(300,'请至少选择一个所属领域！');
        if(empty($_POST['params']['descride']))
            $this->ajaxReturn(300,'请填写项目描述！');
        if(empty($_POST['params']['personal']))
            $this->ajaxReturn(300,'请填写负责人简介！');
        if(empty($_POST['files']))
            $this->ajaxReturn(300,'请上传您的项目计划书！');
        $data['adddate'] = $_POST['editdate'] = date("Y-m-d H:i:s");//编辑时间
        if(!$_POST['id']){//添加项目
            $data['parent_id'] = $_POST['parent_id'] = $result['memberid'];//归属人id
            $_POST['college_id'] = $result['college'];//所属院系
            $_POST['year'] = date("Y");
            $ok = DB('project')->clear()->add($_POST);
            if($ok>=0){
                $data['content']['title'] = '项目信息';
                $data['content']['content'] = '项目创建成功！请等待审核结果！';
                $ok2 = DB('message2')->clear()->add($data);
                if($ok2>=0){
                    setcookie("time",strtotime(date("Y-m-d H:i:s")),null,'/');
                    $this->ajaxReturn(200,"项目提交成功！");
                }
            }
            else		$this->ajaxReturn(300,"项目提交失败！");
        }else{
            $ok = DB('project')->clear()->save($_POST);
            if($ok>=0){
                setcookie("time",strtotime(date("Y-m-d H:i:s")),null,'/');
                $this->ajaxReturn(200,"项目编辑成功！");
            }
            else		$this->ajaxReturn(300,"项目编辑失败！");
        }
    }

    //项目删除
    public function delete_projectAct(){
        //身份判定
        $this->is_student();
        if($_POST){
            if(!My::is_id($_POST['id']))
                $this->ajaxReturn(300,'id有误！');
            $ok = DB('project')->where("id = {$_POST['id']}")->delete();
            if($ok >=0 ){
                setcookie("time",strtotime(date("Y-m-d H:i:s")),null,'/');
                $this->ajaxReturn(200,"删除项目成功！");
            }else
                $this->ajaxReturn(300,"删除项目失败！");
        }
    }

    //项目成员添加
    public function addAct(){
        //身份判定
        $this->is_student();
        if($_POST){
            $result = $this->checkLogin();
            //用户名
            if(!My::is_string($_POST['username'],array('c')))
                $this->ajaxReturn(300,'真实姓名填写有误！');
            //手机号
            if(!My::is_tel($_POST['number']))
                $this->ajaxReturn(300,'请填写正确的手机号！');
            if($_POST['type'] == 'teacher')
                if(!My::is_email($_POST['email']))
                    $this->ajaxReturn(300,'请填写正确的电子邮箱！');
            if($_POST['type'] == 'teacher')
                if(empty($_POST['college']))
                    $this->ajaxReturn(300,'请选择所在院系！');
            if($_POST['type'] == 'teacher')
                if(empty($_POST['professional']))
                    $this->ajaxReturn(300,'请填写导师职称！');
            //获取缓存
            $search['where'] = "1 ";
            //搜索条件
            $search['where'] .= "AND `parent_id`='{$result['memberid']}' ";
            //按申报时间
            if(My::is_id(My::arr2var($_POST,'year'))){
                $year = $_POST['year'];
                $search['where'] .= "AND `year`='{$year}' ";
            }else $search['where'] .= "AND `year`='".date("Y")."' ";
            //缓存时间
            $search['time'] = isset($_COOKIE['time']) ? $_COOKIE['time'] : strtotime(date("Y-m-d H:i:s"));
            $project = My::getCache($search,array('pre'=>'student'));
            $data['members'] = $project['members'];
            if($_POST['type'] == 'student'){
                if(empty($project['members'][$_POST['type']]))
                    $data['members'][$_POST['type']][] = array($_POST['username'],$_POST['number']);
                else{
                    $data['members'][$_POST['type']] = $project['members'][$_POST['type']];
                    $data['members'][$_POST['type']][] = array($_POST['username'],$_POST['number']);
                }
            }
            else if($_POST['type'] == 'teacher'){
                unset($_POST['type']);
                $data['members']['teacher'] = $_POST;
            }
            $data['id'] = $project['id'];//项目id
            $data2['parent_id'] = $project['parent_id'];//账号id
            $ok = DB('project')->clear()->save($data);
            if($ok){
                $data2['adddate'] = strtotime(date("Y-m-d H:i:s"));
                $data2['content']['title'] = isset($_POST['type']) ? '成员信息' : '导师信息';
                $data2['content']['content'] = isset($_POST['type']) ? $_POST['username'].'成员加入成功！' : $_POST['username'].'老师，成为该项目的指导老师';
                $ok2 = DB('message2')->clear()->add($data2);
                if($ok2>=0) {
                    setcookie("time", strtotime(date("Y-m-d H:i:s")), null, '/');
                    $this->ajaxReturn(200, "操作成功！");
                }
            }
            else $this->ajaxReturn(300,"操作失败！");

        }
    }

    //项目成员删除
    public function delete_memberAct(){
        //身份判定
        $this->is_student();
        if($_POST){
            $result = $this->checkLogin();
            if(strlen($_POST['id'])<0)
                $this->ajaxReturn(300,'id有误！');
            //获取缓存
            $search['where'] = "1 ";
            //搜索条件
            $search['where'] .= "AND `parent_id`='{$result['memberid']}' ";
            //按申报时间
            if(My::is_id(My::arr2var($_POST,'year'))){
                $year = $_POST['year'];
                $search['where'] .= "AND `year`='{$year}' ";
            }else $search['where'] .= "AND `year`='".date("Y")."' ";
            //缓存时间
            $search['time'] = isset($_COOKIE['time']) ? $_COOKIE['time'] : strtotime(date("Y-m-d H:i:s"));
            $project = My::getCache($search,array('pre'=>'student'));
            $data2['adddate'] = strtotime(date("Y-m-d H:i:s"));
            $data2['parent_id'] = $project['parent_id'];
            if($_POST['id'] == '-1'){
                $data2['content']['title'] = '导师信息';
                $data2['content']['content'] = $project['members']['teacher']['username'].'导师移除成功！';
                unset($project['members']['teacher']);
            }else{
                $data2['content']['title'] = '成员信息';
                $data2['content']['content'] = $project['members']['student'][$_POST['id']]['0'].'成员移除成功！';
                unset($project['members']['student'][$_POST['id']]);
            }
            $ok = DB('project')->where("id = {$project['id']}")->save(array('members'=>$project['members']));
            if($ok >=0 ){
                $ok2 = DB('message2')->clear()->add($data2);
                if($ok2>=0) {
                    setcookie("time", strtotime(date("Y-m-d H:i:s")), null, '/');
                    $this->ajaxReturn(200, "删除成员成功！");
                }
            }else
                $this->ajaxReturn(300,"删除成员失败！");
        }
    }

    //我的项目-->老师
    public function teacherAct(){
        $result = $this->checkLogin();
        //身份判定
        $this->is_teacher();
        $this->assign('result',$result);
        if(!My::is_id($result['college']))
            $this->ajaxReturn(404,'院系id有误!');

        $search['where'] = "1 ";
        if($result['type'] == '0')//院系身份查询
            $search['where'] .= "AND A.`college_id` = '{$result['college']}' ";
        else if($result['type'] == '1'){//老师身份
            $teacher = '"'.$result['memberid'].'"';
            $search['where'].=" AND A.`teacher` LIKE '%{$teacher}%' ";
        }

        //项目名称或项目创始人
        if(My::arr2var($_GET,'keyword')!=''){
            $keyword = $_GET['keyword'];
            $search['where'].=" AND (A.`project` LIKE '%{$keyword}%' OR B.`username` LIKE '%{$keyword}%') ";
        }
        //院系
        if(My::arr2var($_GET,'auditing_1')!=''){
            $auditing_1 = $_GET['auditing_1'];
            $search['where'].=" AND A.`auditing_1` = '{$auditing_1}' ";
        }
        //cxcyxy
        if(My::arr2var($_GET,'auditing_2')!=''){
            $auditing_2 = $_GET['auditing_2'];
            $search['where'].=" AND A.`auditing_2` = '{$auditing_2}' ";
        }

        $search['field'] = "A.*,B.username as username,B.number as number,B.email as email";
        $search['table'] = "#__project as A";
        $search['join']  = "LEFT JOIN #__homeuser as B ON A.parent_id=B.id ";
        $search['page'] = My::arr2var($_REQUEST,'page').(isset($_SESSION['pagesize'])?$_SESSION['pagesize']:'');//用于参与缓存标识
        //缓存时间
        $search['time'] = isset($_COOKIE['time']) ? $_COOKIE['time'] : strtotime(date("Y-m-d H:i:s"));
        //缓存时间
        $project = My::getCache($search,array('pre'=>'teacher'));
        if($project == ''){
            //page
            $total_sql = DB('')->table($search['table'])->field('1')->join($search['join'])->where($search['where'])->group('A.id')->select(false);
            $project['page'] = My::page(My::sql2count($total_sql));
            //result
            $project['data'] = DB('')->table($search['table'])->field($search['field'])->join($search['join'])->where($search['where'])->group('A.id')->order('editdate DESC,id DESC')->limit($project['page']['limits'])->select();
            foreach($project['data'] as &$value){
                $value['members'] = My::decodeJson($value['members']);
//                $value['files'] = str_replace('/', '-', $value['files']);
            }
            setcookie("time",$search['time'],null,'/');
            My::setCache($search,$project,array('pre'=>'teacher'));
//            echo '没有老师项目缓存，刷新下';
//            exit();
        }
        $this->assign('project',$project);
        $this->assign('verify',C('verify'));
        $this->display();
    }

    //老师-->查看项目详情
    public function teacher_detailAct(){
        $result = $this->checkLogin();
        //身份判定
        $this->is_teacher();
        if(!My::is_id(My::arr2var($_GET,'id')))
            $this->ajaxReturn(300,'id有误！');
        $project = DB('project')->where("id = '{$_GET['id']}'")->cache()->find();//专业
        $project['params'] = My::decodeJson($project['params']);//项目信息
        $project['members'] = My::decodeJson($project['members']);//团队成员
        $project['field'] = explode(",",$project['field']);
        $project['teacher'] = My::decodeJson($project['teacher']); //推荐老师
        $field = C('field');
        if(is_array($project['field']))
            foreach($project['field'] as &$value)
                $value = $field[$value];
        else
            $project['field'] = $field[$project['field']];
        //下载
//        $project['files'] = str_replace('/', '-', $project['files']);
        //所属院系老师
        $search['where'] = "`type` = '1' ";//老师
        if($result['type'] == '0')//管理员身份查询所有老师
            $search['where'] .= "AND `college` = '{$result['college']}'";//老师
        $teacher = DB('homeuser')->where($search['where'])->field('id,username')->select();//专业
        $this->assign('teacher',$teacher);//老师信息
        $this->assign('project',$project);//项目信息
        $this->assign('result',$result);//账号信息
        $this->display();
    }

    //老师审核
    public function teacher_verifyAct(){
        $result = $this->checkLogin();
        //身份判定
        $this->is_teacher();
        $id = $_POST['id'];
        if(!My::is_id($id))
            $this->ajaxReturn(404,'id有误！');
        $data['id'] = $id;
        if(isset($_POST['teacher']))
            $data['teacher'] = $_POST['teacher'];//推荐老师
        if($result['type'] == '0')
            $data['auditing_1'] = $_POST['auditing'];//院系身份审核
        else if($result['type']  == '3')
            $data['auditing_2'] = $_POST['auditing'];//cxcyxy身份审核
        $data2['adddate'] = date("Y-m-d H:i:s");
        $data2['content']['title'] = '审核信息';
        $data2['content']['content'] = '经'."$result[college_c]".'决定，你的项目('."$_POST[project]".')审核结果为';
        if($_POST['auditing'] == '1')
            $data2['content']['content'] .= $_POST['result'] = '审核通过';
        else if($_POST['auditing'] == '2')
            $data2['content']['content'] .= $_POST['result'] = '审核不通过';
        else if($_POST['auditing'] == '0')
            $data2['content']['content'] .= $_POST['result'] = '未审核';
        if(isset($_POST['content']))
            $data2['content']['content1'] = $_POST['content'];
        $data2['parent_id'] = $_POST['parent_id'];
        $ok = DB('project')->clear()->save($data);
        if($ok>0){
            $ok2 = DB('message2')->clear()->add($data2);//通知该学生
            if($ok2){
                setcookie("time", strtotime(date("Y-m-d H:i:s")), null, '/');
                $_POST['type'] = $result['college_c'];
                //发送微信通知
//                if(My::arr2var($_POST,'re_weixin'))
                if($_POST['auditing'] != '0')
                    M('Weixin')->sendWeixin_one($_POST['parent_id'],$_POST);//学生推送消息
                if(isset($_POST['teacher'])){
                    M('Weixin')->sendWeixin($_POST['teacher'],$_POST);//老师推送消息
                    M('Email')->sendEmail($_POST['teacher'],$_POST);//老师推送消息
                }
                $this->ajaxReturn(200,'审核结果提交成功！');
            }else $this->ajaxReturn(300,'留言失败，请重新操作！');
        }else $this->ajaxReturn(300,'审核结果出错，请重新操作！');
    }

    //文件验证
    public function fileAct(){
        if(!empty($_FILES)){
            $upload = new Upload();// 实例化上传类
            $upload->maxSize   = 3145728 ;// 设置附件上传大小
            $upload->allowExts = array('zip', 'doc', 'docx');// 设置附件上传类型
            $upload->savePath  = PUB_DIR.'/share/images/download_file/'; // 设置附件上传（子）目录
            // 上传文件
            if(strstr($_FILES['upload']['name'],"-"))
                $this->ajaxReturn(300,'文件名有误，避免特殊字符!');
            if(file_exists('share/images/download_file/'.$_FILES['upload']['name']))
                $this->ajaxReturn(300,'存在相同的文件名!');
            if(!$upload->upload()) {// 上传错误提示错误信息
                $this->ajaxReturn(300,$upload->getErrorMsg());
            }else{// 上传成功 获取上传文件信息
                $inf= $upload->getUploadFileInfo();
            }
            $this->ajaxReturn(200,'share/images/download_file/'.$inf['0']['savename'],'','',$inf['0']['name']);
        }else
            $this->ajaxReturn(300,'请选择需要上传的文件！');

    }
}
